//
//  SearchController.swift
//  DSP
//
//  Created by tucici on 2024/5/22.
//

import UIKit
import CoreBluetooth
import TCCKit

class SearchController: DSAlertController {
    private var bgView : UIView!
    private var theme : UILabel!
    private var line : UIView!
    private var footer : SettingsFooter!
    override func viewDidLoad() {
        super.viewDidLoad()
        initUI()
        initData()
    }
    
    override func initUI() {
        
        bgView = UIView()
        bgView.bgHexColor = "#FFFFFF"
        bgView.cornerRadius = 10.k_h
        
        theme = UILabel()
        theme.text = "Devices"
        theme.font = font(18,.bold)
        theme.textHexColor = "#000000"
        
        line = UIView()
        line.bgHexColor = "#000000"
        
        footer = SettingsFooter()
        footer.array = ["Refresh Device List","Reset DSP Tuning","Version 1.0"]
        footer.block = {[weak self] text in
            self?.action(text)
        }
        
        tableViewStyle = .grouped
        tableView.backgroundColor = "#FFFFFF".color()
        tableView.delegate = self
        tableView.dataSource = self
        tableView.register(DeviceCell.self, forCellReuseIdentifier: DeviceCell.ID())
        tableView.setupRefreshing()
        tableView.setHeaderTitle(title: "Searching...", state: .refreshing)
        (tableView.mj_header as? MJRefreshStateHeader)?.lastUpdatedTimeText = { date in
            return ""
        }
        tableView.updateBlock = {[weak self] in
            self?.initData()
        }
        
        view.addSubview(bgView)
        bgView.addSubview(theme)
        bgView.addSubview(line)
        bgView.addSubview(tableView)
        bgView.addSubview(footer)
        
        bgView.snp.makeConstraints { make in
            make.left.right.equalToSuperview().inset(k_w(30))
            make.top.bottom.equalToSuperview().inset(k_h(70))
        }
        
        theme.snp.makeConstraints { make in
            make.centerX.top.equalToSuperview()
            make.height.equalTo(50)
        }
        
        line.snp.makeConstraints { make in
            make.top.equalTo(theme.snp.bottom).offset(0)
            make.left.right.equalToSuperview().inset(10)
            make.height.equalTo(1)
        }
        
        tableView.snp.makeConstraints { make in
            make.top.equalTo(line.snp.bottom)
            make.left.right.equalToSuperview()
        }
        
        footer.snp.makeConstraints { make in
            make.top.equalTo(tableView.snp.bottom)
            make.left.right.bottom.equalToSuperview()
        }
    }
    
    private var array = [DSPeripheral](){
        didSet{
            let copy = array.map{$0.copy()}
            RealmHelper.updateObjects(objects:copy)
            tableView.reloadData()
        }
    }
    
    override var connectStatus: BLEStatus{
        didSet{
            tableView.reloadData()
        }
    }
    func action(_ title:String){
        switch title{
        case "Refresh Device List":
            tableView.mj_header?.beginRefreshing()
        case "Reset DSP Tuning":
            let vc = AlertController()
            vc.msg.text = "Are you sure to reset DSP tuning?"
            vc.style = .normal
            vc.leftBtnTitle = "NO"
            vc.rightBtnTitle = "YES"
            vc.rightBlock = { _ in
                APP.resetCH()
                CLHUD(type: .loading, callBack: {
                    CLHUD("Reset DSP tuning successfully",type: .info, callBack: nil)
                })
            }
            present(vc, animated: false)
        case "Version 1.0":
            break
        default:
            break
        }
    }
    
    override func initData(){
        let localArray = RealmHelper.queryObject(objectClass: DSPeripheral()).map{$0.copy() as! DSPeripheral}
        array.removeAll()
        
        BLE.scanWithOther = { peripheral in
            _ = String(format: "%.2X%.2X", peripheral.advertData[0],peripheral.advertData[1])
            //return productName.contains(product) || OTAName.contains(peripheral.name ?? "")
            //if peripheral.kRSSI < -70{return false}
            return peripheral.name?.contains(DeviceName) ?? false
        }
        
        BLE.startScanOneByOne {[weak self] peripheral in
            guard let self = self else{return}
            if !self.array.contains(where:{$0.uuid.count > 0 && ($0.uuid == peripheral.mac || $0.uuid == peripheral.identifier.uuidString)}){
                let per = localArray.first(where: {$0.uuid.count > 0 && ($0.uuid == peripheral.mac || $0.uuid == peripheral.identifier.uuidString)}) ?? DSPeripheral(peripheral: peripheral)
                per.peripheral = peripheral
                self.array.append(per)
            }
        }
        
        DispatchQueue.main.asyncAfter(deadline: .now() + 6, execute: {[weak self] in
            BLE.stopScan()
            self?.tableView.endRefreshing()
        })
        
        BLE.connectBlock = { status in
            print("====statas = \(status)")
            if status == .connectedSucces{
                BLE.delegate = DSBleDataTool.share
                DSShowView.show()
            }
        }
    }
    
    func changeName(_ per:DSPeripheral){
        let vc = AlertController()
        vc.msg.text = per.name
        vc.style = .input
        vc.rightBlock = {[weak self] content in
            if content.count <= 0 {return}
            per.name = content
            RealmHelper.updateObject(object: per.copy())
            self?.tableView.reloadData()
        }
        present(vc, animated: false)
    }
}
//MARK: - UITableViewDataSource
extension SearchController:UITableViewDataSource{
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return array.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: DeviceCell.ID()) as! DeviceCell
        let per = array[indexPath.row]
        cell.peripheral = per
        cell.line.isHidden = indexPath.row == array.count - 1
        cell.block = { ison in
            ison ? BLE.connect(per.peripheral) : BLE.disConnect(per.peripheral)
        }
        
        cell.longpress.minimumPressDuration = 0.5
        cell.longPressBlock = {[weak self] in
            self?.changeName(per)
        }
        return cell
    }
}
//MARK: - UITableViewDelegate
extension SearchController:UITableViewDelegate{
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        
    }
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 0.01
    }
    
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return 0.01
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        return nil
    }
    
    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        return nil
    }
}
